// packageA/pages/equipmentStockDetail/equipmentStockDetail.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
import Base64 from '../../../utils/Base64.js';
const util = require('../../../utils/util');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //当前tab
    active: 0,
    //传参
    paramObj:null,
    //传参来的id
    id:null,
    //修改信息回显
    editInfo:{},
    //提交按钮禁用
    disabled:false,
    //验收项
    checkList: [],
    //查看or验收
    mark:'',
    //折叠面板
    activePart: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);
      console.log('设备库存详情传参');
      console.log(paramObj);

      this.setData({
        paramObj: paramObj,
        mark: paramObj.mark
      })

      if(paramObj.id){
        this.setData({
          id: paramObj.id
        })
        this.getInfo();
      }
    }
  },

  //获取修改的数据
  getInfo(){
    let param = {
      isAuth: false,
      className: 'repertory',
      data: {
        id:this.data.id,
        selectFields: ["id","equipmentNo","imei","type", "state", "num","category", "createDate", "name", "spec","unit","depot","relationOrderNo","leaseRecord","ioStorageDetail","performance","remarks","checkRecord","maintain","testRecord","checkRemarks","orderObj","service","keepAccounts","dataAuthority","accountingPrice"]
      }
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result[0];

        //获取检测字典
        if(this.data.mark=='check'){
          if(result.category && result.category.length){
            this.getCheckTypeMap(result.category);
          }
        }

        //状态
        switch(result.state){
          case 1:
            result.stateWord='待验收';
            result.stateClass='c-4';
            break;
          case 2:
            result.stateWord='待保养';
            result.stateClass='c-7';
            break;
          case 3:
            result.stateWord='待检测';
            result.stateClass='c-2';
            break;
          case 4:
            result.stateWord='已完成';
            result.stateClass='c-1';
            break;
          case 5:
            result.stateWord='已核算';
            result.stateClass='c-5';
            break;
          case 6:
            result.stateWord='已预订';
            result.stateClass='c-4';
            break;
          case 7:
            result.stateWord='已出库';
            result.stateClass='c-6';
            break;
        }
        
        if(result.leaseRecord && result.leaseRecord.length){
          let allLeaseTime = 0;
          result.leaseRecord.forEach(item=>{
            //使用时长
            allLeaseTime += parseInt(item.leaseDuration);

            //使用记录日期
            if(item.orderObj.contractTime){
              item.orderObj.contractTime=util.timeFormat(item.orderObj.contractTime);
            }
            if(item.createDate){
              item.createDate=util.timeFormat(item.createDate);
            }
          });
          result.allLeaseTime=allLeaseTime;
        }

        //验收信息
        if(result.checkRecord && result.checkRecord.length){
          result.checkContenrMap=result.checkRecord[0].checkContenrMap;
        }
        
        //出入库时间
        if(result.ioStorageDetail && result.ioStorageDetail.length){
          result.ioStorageDetail.forEach(item=>{
            if(item.createTime){
              item.createTime=util.timeFormat(item.createTime);
            }
          });
        }
        
        //保养时间
        if(result.maintain && result.maintain.length){
          result.maintain.forEach(item=>{
            if(item.startDate){
              item.startDate=util.timeFormat(item.startDate);
            }
            if(item.startDate){
              item.endDate=util.timeFormat(item.endDate);
            }
          });
        }

        //检测时间
        if(result.testRecord && result.testRecord.length){
          result.testRecord.forEach(item=>{
            if(item.startDate){
              item.startDate=util.timeFormat(item.startDate);
            }
            if(item.startDate){
              item.endDate=util.timeFormat(item.endDate);
            }
          });
        }
        
        console.log('设备库存信息');
        console.log(result);

        this.setData({
          editInfo: result
        })
      }
    }).catch((error) => {
    })
  },

  //切换tab
  onChange(event) {
    //event.detail.name
  },

  //检测字典
  getCheckTypeMap(category){
    let param = {
      isAuth: false,
      className: 'dictionary',
      data: {
        searchAll: true,
        used: true,
        categories: category,
        key: 'checkContent',
        selectFields: ['id', 'key', 'used','content','category','checkType']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let arr = res.data.data.result;
        let map = new Map();
        let checkArr = [];
        arr.forEach(item => {
          if (map.get(item.checkType.name)) {
            item.value = "";
            let arr = map.get(item.checkType.name);
            arr.push(item);
            map.set(item.checkType.name, arr);
          } else {
            checkArr = [];
            item.value = "";
            checkArr.push(item);
            map.set(item.checkType.name, checkArr);
          }
        });
        let list = [];
        map.forEach((value,key) => {
          list.push({
            key: key,
            data: value
          });
        });

        console.log('检测项');
        console.log(list);

        list.forEach(item => {
          let arrs=item.data;
          for(let i=0;i<arrs.length;i++){
            arrs[i].value=1;
          }
        });
       
        this.setData({
          checkList: list
        })
      }
    }).catch((error) => {
    })
  },

  //选择良好/异常
  onSelectCheck(e){
    let dataset=e.currentTarget.dataset;
    let list=this.data.checkList;

    list.forEach(item => {
      let arr=item.data;
		  for(let i=0;i<arr.length;i++){
        if(arr[i].id==dataset.id){
          arr[i].value=dataset.mark;
        }
      }
    });
    
    this.setData({
      checkList: list
    })
  },

  //验收提交表单
  confirmForm(e){
    //避免表单重复提交-先禁用按钮
    this.setData({
      disabled:true
    })
 
    let obj=e.detail.value;
    let editInfo=this.data.editInfo;

    //新旧程度非空
    let performance=obj.performance.trim();
    if(!this.formNotEmpty(performance,'performanceMessage','请输入新旧程度')){
      return;
    }

    editInfo.appId = [app.globalData.myAppId];
    editInfo.state = 2;
    editInfo.performance = performance;
    editInfo.remarks = obj.remarks.trim();
    editInfo.checkRemarks = obj.checkRemarks.trim();
    editInfo.checkContenrMap = this.data.checkList; 

    //console.log(editInfo);

    //避免表单重复提交
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '数据提交中...'
    });

    CommonService.checkItem(editInfo).then(res=>{
      this.setData({
        disabled:false
      })
      if (res.statusCode == 200 && res.data.success == true){
        Toast.success('成功');
        setTimeout(() => {
          //返回列表页并刷新数据
          this.backAndRefresh();
        }, 1000);
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })  
  },

  //返回列表页并刷新数据
  backAndRefresh(){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];

    prevPage.refreshListAndPage();
    wx.navigateBack();
  },

  //非空验证（field要先去掉空格）
  formNotEmpty(field,messageField,messageCon){
    if(!field){
      let obj = {};
      obj[messageField] = messageCon;
      obj['disabled'] = true;
      this.setData(obj);
      return false;
    }else{
      return true;
    }
  },

  //用户输入时清除错误提示
  clearMessage(e) {
    let field = e.target.dataset.message;
    let obj = {};
    obj[field] = "";
    obj['disabled'] = false;
    this.setData(obj);
  },

  //切换折叠面板
  onChangePart(event) {
    this.setData({
      activePart: event.detail,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})